<script setup>
import InputText from "../components/InputText.vue";
import InputSelect from "../components/InputSelect.vue";
import Button from "../components/Button.vue";
import IconSvg from "../components/IconSvg.vue";
import DataTable from "../components/DataTable.vue";
import Model from "../components/Model.vue";
import PaginationBasic from "../components/PaginationBasic.vue";
import Message from "../components/Message/Message.js";
import {
  RoleConstants
} from '../utils/constants.js';
import { ref, onMounted } from "vue"
import axios from "../axios/axios.js";
const searchInfo = ref({ username: '', role: '' });
const showAddModel = ref(false)
const addInfo = ref({})
const operateItem = ref()
const isAdd = ref(false)
const showRegisterModel = ref(false)
const roleOption = ref([])
const pageData = ref({
  currentPage: 1,
  total: 0,
  pageSize: 10,
})
const pageRegisterData = ref({
  currentPage: 1,
  total: 0,
  pageSize: 10,
})
// 页码变化时触发
const handlePageChange = (page) => {
  pageData.value.currentPage = page
  // 这里可以调用接口加载对应页的数据
  getData()
}
const handleRegisterPageChange = (page) => {
  pageRegisterData.value.currentPage = page
  getRegisterData()
}

const tableData = ref()
const tableRegisterData = ref()
// 列配置
const tableColumns = ref([
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'name', title: '姓名', dataIndex: 'name' },
  { key: 'username', title: '用户名', dataIndex: 'username' },
  { key: 'password', title: '密码', dataIndex: 'password' },
  { key: 'role', title: '角色', dataIndex: 'role' },
  { key: 'identificationcode', title: '标识', dataIndex: 'identificationcode' },
  { key: 'cardnumber', title: '绑定卡号', dataIndex: 'cardnumber' },
  { key: 'createTime', title: '创建时间', dataIndex: 'createtime' },
  { key: 'action', title: '操作', dataIndex: 'action' }
])
const getRoleLabel = (roleValue) => {
  const role = RoleConstants.TYPE_MAP[roleValue]
  return role ? role : '未知角色';
};
const openAddModel = () => {
  getRoleData()
  isAdd.value = true
  showAddModel.value = true
}
const handleConfirm = () => {
  if (!addInfo.value.name || addInfo.value.name == "") {
    Message.warn('请输入用户名')
    return
  }
  if (!addInfo.value.username || addInfo.value.username == "") {
    Message.warn('请输入用户名')
    return
  }
  if (!addInfo.value.password || addInfo.value.password == "") {
    Message.warn('请输入密码')
    return
  }
  if (!addInfo.value.role || addInfo.value.role == "") {
    Message.warn('请选择角色')
    return
  }

  if (isAdd.value) {
    Message.success('正在添加')
    axios.post("/api/user/save", {
      name: addInfo.value.name,
      username: addInfo.value.username,
      password: addInfo.value.password,
      role: addInfo.value.role
    }).then(res => {
      if (res.data.Code == "200") {
        Message.success('添加成功')
        showAddModel.value = false
        isAdd.value = false
        addInfo.value = {}
        getData()
      } else {
        Message.warn(res.data.Msg)
      }
    })
  } else {
    axios.post('/api/user/updatebyid',
      {
        id: operateItem.value.id,
        name: addInfo.value.name,
        username: addInfo.value.username,
        password: addInfo.value.password,
        role: addInfo.value.role
      }).then(res => {
        if (res.data.Code == "200") {
          Message.success('修改成功')
          showAddModel.value = false
          getData()
          addInfo.value = {}
          operateItem.value = {}
        } else {
          Message.warn(res.data.Msg)
        }
      })

  }
}
const handleCancel = () => {
  isAdd.value = false
  addInfo.value = {}
  showAddModel.value = false
  operateItem.value = {}
}
const handleEdit = (item) => {
  operateItem.value = item
  showAddModel.value = true
  addInfo.value = {
    name: item.name,
    username: item.username,
    password: item.password,
    role: item.role
  }
}
const handleDelete = (item) => {
  axios.get('/api/user/delete?id=' + item.id).then(res => {
    if (res.data.Code == "200") {
      Message.success('删除成功')
      getData()
    } else {
      Message.warn(res.data.Msg)
    }
  })
}
const resetSearch = () => {
  searchInfo.value = { username: '', role: '' }
  getData()
}
const openRegisterModel = () => {
  showRegisterModel.value = true
  getRegisterData()
}
const getRegisterData = () => {
  var url = '/api/user/registerinfo?pageNum=' + pageRegisterData.value.currentPage + "&pageSize=" + pageRegisterData.value.pageSize
  axios.get(url).then(res => {
    tableRegisterData.value = res.data.Data.records
    pageRegisterData.value = {
      currentPage: pageRegisterData.value.currentPage === undefined ? 1 : pageRegisterData.value.currentPage,
      total: res.data.Data.total,
      pageSize: res.data.Data.size,
    }
  })
}
const handleRegister = (item) => {
  axios.get('/api/user/review?status=1&id=' + item.id).then(res => {
    if (res.data.Code == 200) {
      Message.success('审核通过')
      showRegisterModel.value = false
      getData()
    } else {
      Message.error(res.data.Msg)
    }
  })
}
const getData = () => {
  var url = '/api/user/select?pageNum=' + pageData.value.currentPage + "&pageSize=" + pageData.value.pageSize
  if (searchInfo.value.username !== '') {
    url = url + "&username=" + searchInfo.value.username
  }
  if (searchInfo.value.role !== '') {
    url = url + "&role=" + searchInfo.value.role
  }
  axios.get(url).then(res => {
    tableData.value = res.data.Data.records
    pageData.value = {
      currentPage: pageData.value.currentPage === undefined ? 1 : pageData.value.currentPage,
      total: res.data.Data.total,
      pageSize: res.data.Data.size,
    }
  })
}
const getRoleData = () => {
  axios.get("/api/role/selectall").then(res => {
    const roleList = res.data.Data || [];
    var options = [];
    roleList.forEach(role => {
      const rolename = role.rolename;
      const typeMapEntries = Object.entries(RoleConstants.TYPE_MAP);
      const matchedEntry = typeMapEntries.find(([id, name]) => {
        return name === rolename;
      });
      const [id, name] = matchedEntry;
      options.push({ value: id, label: name })
    });
    roleOption.value = options
  })
}

onMounted(() => {
  getData()
  getRoleData()
});
</script>
<template>
  <div class="bg-[white] w-full h-full pt-[40px] px-[40px] text-base flex flex-col">
    <div class="flex justify-start items-center">
      <InputText type="text" label="用户名" placeholder="请输入用户名" class="w-[260px] mr-[20px]"
        v-model="searchInfo.username" />
      <InputSelect label="角色" class="w-[260px] mr-[20px]" v-model="searchInfo.role">
        <option value="">请选择角色</option>
        <option v-for="value in roleOption" :value="value.value">{{ value.label }}</option>
      </InputSelect>
      <Button type="primary" content="查询" class="mr-[20px]" @click="getData">
        <template #icon>
          <IconSvg name="search" class="w-[18px] h-[18px]"></IconSvg>
        </template>
      </Button>
      <Button content="重置" class="mr-[20px]" @click="resetSearch">
        <template #icon>
          <IconSvg name="refresh" class="w-[15px] h-[15px]"></IconSvg>
        </template>
      </Button>
    </div>
    <div class="mt-[40px] flex-1 overflow-auto">
      <div class="flex justify-start items-center">
        <Button type="primary" content="新增" class="mr-[20px]" @click="openAddModel">
          <template #icon>
            <IconSvg name="add" class="w-[18px] h-[18px]"></IconSvg>
          </template>
        </Button>
        <Button type="primary" content="审核" class="mr-[20px]" @click="openRegisterModel">
        </Button>
      </div>

      <DataTable :dataSource="tableData" :columns="tableColumns" class="mt-[20px]">
        <template #cardnumber="{ item }">
          {{ item.cardnumber != null ? item.cardnumber : '未绑定' }}
        </template>
        <template #role="{ item }">
          {{ getRoleLabel(item.role) }}
        </template>
        <template #action="{ item }">
          <a class="text-[#165dff] cursor-pointer">绑卡</a>
          <a @click="handleEdit(item)" class="ml-2 text-[#165dff] cursor-pointer">编辑</a>
          <a @click="handleDelete(item)" class="ml-2 text-red-500 cursor-pointer">删除</a>
        </template>
      </DataTable>

    </div>
    <div class="flex justify-end items-center my-4">
      <label class="font-medium">共{{ pageData.total }}条</label>
      <PaginationBasic :total="pageData.total" :page-size="pageData.pageSize" v-model:current="pageData.currentPage"
        @onPageChange="handlePageChange" />
    </div>

    <Model :show="showAddModel" @close="!showAddModel">
      <template #header>
        <h3>用户操作</h3>
      </template>
      <template #body>
        <div class="flex flex-col gap-[15px]">
          <InputText type="text" label="姓名" placeholder="请输入姓名" class="w-[300px]" v-model="addInfo.name"
            label-width="50px" />
          <InputText type="text" label="用户名" placeholder="请输入用户名" class="w-[300px]" v-model="addInfo.username"
            label-width="50px" />
          <InputText type="text" label="密码" placeholder="请输入密码" class="w-[300px]" v-model="addInfo.password"
            label-width="50px" />
          <InputSelect label="角色" v-model="addInfo.role" class="w-[300px]" label-width="50px">
            <option v-for="value in roleOption" :value="value.value">{{ value.label }}</option>
          </InputSelect>
        </div>

      </template>
      <template #footer>
        <div class="flex justify-around">
          <Button content="取消" @click="handleCancel"></Button>
          <Button type="primary" content="确定" @click="handleConfirm"></Button>
        </div>
      </template>
    </Model>
    <Model :show="showRegisterModel" @close="!showRegisterModel">
      <template #header>
        <h3>审核用户</h3>
      </template>
      <template #body>
        <DataTable :dataSource="tableRegisterData" :columns="tableColumns" class="mt-[20px]">
          <template #cardnumber="{ item }">
            {{ item.cardnumber != null ? item.cardnumber : '未绑定' }}
          </template>
          <template #role="{ item }">
            {{ getRoleLabel(item.role) }}
          </template>
          <template #action="{ item }">
            <a class="text-[#165dff] cursor-pointer" @click="handleRegister(item)">确认</a>
          </template>
        </DataTable>
        <div class="flex justify-end items-center mt-4">
          <label class="font-medium">共{{ pageRegisterData.total }}条</label>
          <PaginationBasic :total="pageRegisterData.total" :page-size="pageRegisterData.pageSize"
            v-model:current="pageRegisterData.currentPage" @onPageChange="handleRegisterPageChange" />
        </div>

      </template>
      <template #footer>
        <div class="flex justify-end">
          <Button content="取消" @click="() => { showRegisterModel = false }"></Button>
        </div>
      </template>
    </Model>
  </div>
</template>

<style scoped></style>
